package com.asset.salesforce.validator;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.asset.salesforce.domain.Appointment;
import com.asset.salesforce.form.AppointmentForm;
import com.asset.salesforce.service.AppointmentService;

public class AppointmentNotExistConstraintValidator implements ConstraintValidator<AppointmentNotExist, Object> {

        @Autowired
        private AppointmentService appointmentService;

        public void initialize(AppointmentNotExist arg0) {
                // TODO Auto-generated method stub
               
        }

        public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
                boolean success = false;
                AppointmentForm appointmentForm = (AppointmentForm)object;
                List<Appointment>appointments= appointmentService.getAppointmentEventsByEmployeeId(appointmentForm.getEmpId(),appointmentForm.getParentId());
               
                String targetStartTime = appointmentForm.getTime();
                String targetEndTime = appointmentForm.getMeetingDuration();

                if(targetStartTime!=null&&!targetStartTime.equalsIgnoreCase("")||targetEndTime!=null&&!targetStartTime.equalsIgnoreCase("")){
                	 if(targetStartTime!=null&&!(targetStartTime.equalsIgnoreCase(""))){
                     	if(targetEndTime!=null&&!(targetEndTime.equalsIgnoreCase(""))){
                                ///success = true;
                String[] TargetStartTimeForTime = targetStartTime.split(":");
                Integer targetStartTime1 = (Integer.parseInt(TargetStartTimeForTime[0])*60)+Integer.parseInt(TargetStartTimeForTime[1]);                
               
                String[] targetEndTimeForTime = targetEndTime.split(":");
                Integer targetEndTime1 = (Integer.parseInt(targetEndTimeForTime[0])*60)+Integer.parseInt(targetEndTimeForTime[1]);
               
                String dateValue = appointmentForm.getDate();
                String[] TargetDate = dateValue.split("/");
                for (int i = 0; i < TargetDate.length; i++) {
                        System.out.println(TargetDate[i]);
                }
                String dayOfWeek = null;
                try {
                        String dateString = String.format(appointmentForm.getDate());
                        Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateString);
                        dayOfWeek = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);
                        System.out.println(dayOfWeek);
                } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                }
                if(appointments.size()==0){
                        success=true;
                }
                else{
                for (Appointment appointment : appointments) {
                        String sourceStartTime = appointment.getTime();
                        String []sourceStartTimeFromDatabase = sourceStartTime.split(":");
                        Integer sourceStartTime1 = -1;
                        if(sourceStartTimeFromDatabase.length==2&&isNumeric(sourceStartTimeFromDatabase[0])&&isNumeric(sourceStartTimeFromDatabase[1])){
                                sourceStartTime1 = (Integer.parseInt(sourceStartTimeFromDatabase[0])*60)+Integer.parseInt(sourceStartTimeFromDatabase[1]);
                        }
                       
                        String sourceEndTime = appointment.getMeetingDuration();
                        String []sourceEndTimeFromDatabase = sourceEndTime.split(":");
                        Integer sourceEndTime1 = -1;
                        if(sourceEndTimeFromDatabase.length==2&&isNumeric(sourceEndTimeFromDatabase[0])&&isNumeric(sourceEndTimeFromDatabase[1])){
                                sourceEndTime1 = (Integer.parseInt(sourceEndTimeFromDatabase[0])*60)+Integer.parseInt(sourceEndTimeFromDatabase[1]);
                        }
                        String sdateValue = appointment.getDate().toString().substring(0, 10);
                        String[] sourceTargetDate = sdateValue.split("-");
                        for (int i = 0; i < sourceTargetDate.length; i++) {
                                System.out.println(sourceTargetDate[i]);
                        }
                        String dateFinal = sourceTargetDate[2]+"/" +sourceTargetDate[1]+"/" +sourceTargetDate[0];
                        if(!dateValue.equals(dateFinal)){
                        	if(!(appointmentForm.getDay().equals(""))&&appointmentForm.getDay()!=null){
                        		if(dayOfWeek.equals(appointmentForm.getDay())){
                                    success=true;
                            }   
                                else{
                                        constraintValidatorContext.buildConstraintViolationWithTemplate("The Day you Entered must match the date").addNode("day").addConstraintViolation();
                                        constraintValidatorContext.disableDefaultConstraintViolation();
                                        return success;
                                }
                        	}
                        	else{
                        		success=false;
                        	}
                        }
                        else{
                                        if(sourceStartTime1 == -1 || sourceEndTime1 == -1 ){
                                                success = true;
                                                }else{
                                                        if(targetStartTime1>=sourceEndTime1 && targetEndTime1>targetStartTime1
                                                                        ||targetEndTime1<=sourceStartTime1&&targetStartTime1<targetEndTime1){
                                                                 success = true;
                                                        }
                                                        else{
                                                                 success=false;
                                                        }
                                                }
                }
                               
                }
                }
                return success;
                        }
                     	else{success=true;}
                	 }
                else{
                	success=true;
                }
                }
                else{
                	success=true;
                }
                return success;
        }
        public  boolean isNumeric(String str){
            for (char c : str.toCharArray())
            {
                if (!Character.isDigit(c)) return false;
            }
            return true;
        }
}
